from rest_framework import serializers
from .models import *
from django.db.models import Q

class GoodCategorySerializer3(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields = '__all__'


class GoodCategorySerializer2(serializers.ModelSerializer):
    sub_cat = GoodCategorySerializer3(many=True)
    class Meta:
        model = GoodsCategory
        fields = '__all__'

#商品类别序列化
class GoodCategorySerializer(serializers.ModelSerializer):
    sub_cat = GoodCategorySerializer2(many=True)
    class Meta:
        model = GoodsCategory
        fields = '__all__'

#商品图片序列化
class GoodImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsImage
        fields = '__all__'


#商品序列化
class GoodSerializer(serializers.ModelSerializer):
    images = GoodImageSerializer(many=True)
    class Meta:
        model = Goods
        fields = '__all__'

#轮播图序列化
class BannerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Banner
        fields = '__all__'

class BrandSerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategoryBrand
        fields = '__all__'

#首页商品分类序列化
class IndexCategorySerializer(serializers.ModelSerializer):
    brands = BrandSerializer(many=True)
    sub_cat = GoodCategorySerializer2(many=True)
    goods = serializers.SerializerMethodField()
    ad_goods = serializers.SerializerMethodField()


    def get_ad_goods(self,obj):
        goods_json = {}
        ad_goods = IndexAd.objects.filter(category_id=obj.id)
        if ad_goods:
            good_ins = ad_goods[0].goods
            goods_json = GoodSerializer(good_ins, many=False, context={'request':self.context['request']}).data
        return goods_json

    def get_goods(self, obj):
        all_goods = Goods.objects.filter(Q(category_id=obj.id) |
                                         Q(category__parent_category_id=obj.id) |
                                         Q(category__parent_category__parent_category_id=obj.id))
        goods_serializer = GoodSerializer(all_goods, many=True, context={'request': self.context['request']})
        return goods_serializer.data
    class Meta:
        model = GoodsCategory
        fields = '__all__'